package com.loe.http;

import android.content.ContentValues;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.provider.MediaStore;

import com.loe.http.callback.HttpBooleanCallBack;
import com.loe.http.callback.HttpFileCallback;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

public class HttpFileUtil
{
    public static final String ASSETS = "file:///android_asset/";

    public static String privateCachePath = "/data/cache/loe/";
    public static String privateFilesPath = "/data/files/loe/";

    public static String extCachePath = "/sdcard/cache/loe/";
    public static String extFilesPath = "/sdcard/files/loe/";
    public static String downPath = extFilesPath + "down/";
    public static String downApkPath = extFilesPath + "down_apk/";

    public static Context context;

    public static void init(Context context)
    {
        HttpFileUtil.context = context;
        privateFilesPath = context.getFilesDir().getAbsolutePath() + "/loe/";
        privateCachePath = context.getCacheDir().getAbsolutePath() + "/loe/";
        extFilesPath = context.getExternalFilesDir("").getAbsolutePath() + "/loe/";
        extCachePath = context.getExternalCacheDir().getAbsolutePath() + "/loe/";
        downPath = extFilesPath + "down/";
        downApkPath = extFilesPath + "down_apk/";
    }

    /**
     * 保存文件
     */
    public static void assetsToFile(String path, final String nPath, final HttpFileCallback fileCallback)
    {
        final String oldPath = path.replace(ASSETS, "");

        new Thread()
        {
            @Override
            public void run()
            {
                File file = null;
                FileOutputStream fos = null;
                try
                {
                    InputStream is = context.getAssets().open(oldPath);

                    file = new File(nPath);
                    // 如果文件存在则删除
                    if (file.exists())
                    {
                        delete(file);
                    }
                    // 如果文件夹路径不存在，则创建路径
                    if (!file.getParentFile().exists())
                    {
                        file.getParentFile().mkdirs();
                    }
                    fos = new FileOutputStream(file, true);
                    byte[] buffer = new byte[2048];
                    int byteCount = 0;
                    while ((byteCount = is.read(buffer)) != -1)
                    {
                        fos.write(buffer, 0, byteCount);
                    }
                    fos.flush();
                    is.close();
                    fos.close();
                    fileCallback.response(file);
                } catch (Exception e)
                {
                    if (fos != null)
                    {
                        try
                        {
                            fos.close();
                        } catch (Exception e0)
                        {
                        }
                    }
                    fileCallback.error();
                }
            }
        }.start();
    }

    /**
     * 保存文件
     */
    public static File assetsToFile(String assetsPath, final String nPath) throws Exception
    {
        final String oldPath = assetsPath.replace(ASSETS, "");

        File file = null;
        FileOutputStream fos = null;
        try
        {
            InputStream is = context.getAssets().open(oldPath);

            file = new File(nPath);
            // 如果文件存在则删除
            if (file.exists())
            {
                delete(file);
            }
            // 如果文件夹路径不存在，则创建路径
            if (!file.getParentFile().exists())
            {
                file.getParentFile().mkdirs();
            }
            fos = new FileOutputStream(file, true);
            byte[] buffer = new byte[2048];
            int byteCount = 0;
            while ((byteCount = is.read(buffer)) != -1)
            {
                fos.write(buffer, 0, byteCount);
            }
            fos.flush();
            is.close();
            fos.close();
            return file;
        } catch (Exception e)
        {
            if (fos != null)
            {
                try
                {
                    fos.close();
                } catch (Exception e0)
                {
                }
            }
        }
        throw new Exception("assets转化出错");
    }

    /**
     * 获取扩展名
     */
    public static String getExtension(String path)
    {
        int start = path.lastIndexOf(".");
        int end = path.indexOf("?");
        if (start < 0)
        {
            return "";
        }
        if (end > start)
        {
            return path.substring(start + 1, end).toLowerCase();
        }
        return path.substring(start + 1).toLowerCase();
    }

    /**
     * 获取url文件名和扩展名
     */
    public static String getUrlNameExt(String url)
    {
        int start = url.lastIndexOf("/");
        int end = url.indexOf("?");
        if (start < 0)
        {
            return url;
        }
        if (end > start)
        {
            return url.substring(start + 1, end);
        }
        return url.substring(start + 1);
    }

    /**
     * 删除文件（文件夹）
     */
    public static boolean delete(File file)
    {
        if (!file.exists())
        {
            return true;
        }
        if (file.isFile())
        {
            return file.delete();
        }
        else
        {
            if (file.isDirectory())
            {
                File[] childFiles = file.listFiles();
                if (childFiles == null || childFiles.length == 0)
                {
                    return file.delete();
                }

                for (int i = 0; i < childFiles.length; i++)
                {
                    delete(childFiles[i]);
                }
                return file.delete();
            }
        }
        return false;
    }

    /**
     * 创建temp
     */
    public static File getTemp(String path)
    {
        return getTemp(path, null);
    }

    public static File getTemp(String path, String flag)
    {
        if (flag == null || flag.isEmpty())
        {
            path = extCachePath + getUrlNameExt(path) + ".temp";
        }
        else
        {
            path = extCachePath + getUrlNameExt(path) + "-" + flag + ".temp";
        }
        File file = new File(path);
        return file;
    }

    /**
     * 清除down文件夹
     */
    public static void clearDown()
    {
        delete(new File(downPath));
    }

    /**
     * 清除down_apk文件夹
     */
    public static void clearDownApk()
    {
        delete(new File(downApkPath));
    }

    /**
     * 清理cache文件夹
     */
    public static boolean clearCache()
    {
        return delete(new File(extCachePath));
    }

    /**
     * 重命名
     */
    public static File renameAll(File file, String newPath)
    {
        File newFile = new File(newPath);
        if (newFile.exists())
        {
            newFile.delete();
        }
        else
        {
            if (!newFile.getParentFile().exists())
            {
                newFile.getParentFile().mkdirs();
            }
        }
        file.renameTo(newFile);
        if(!newFile.exists())
        {
            copyFile(file.getAbsolutePath(), newFile.getAbsolutePath());
        }
        return newFile;
    }

    /**
     * 文件的复制操作方法
     */
    public static File copyFile(String path, String newPath)
    {
        File fromFile = new File(path);
        File toFile = new File(newPath);
        if (!fromFile.exists())
        {
            return null;
        }
        if (!fromFile.isFile())
        {
            return null;
        }
        if (!fromFile.canRead())
        {
            return null;
        }
        if (!toFile.getParentFile().exists())
        {
            toFile.getParentFile().mkdirs();
        }
        if (toFile.exists())
        {
            toFile.delete();
        }
        try
        {
            FileInputStream fosfrom = new FileInputStream(fromFile);
            FileOutputStream fosto = new FileOutputStream(toFile);
            byte[] bt = new byte[1024];
            int c = fosfrom.read(bt);
            while (c > 0)
            {
                fosto.write(bt, 0, c);
                c = fosfrom.read(bt);
            }
            //关闭输入、输出流
            fosfrom.close();
            fosto.close();
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return toFile;
    }

    /**
     * 获取剩余空间
     */
    public static long getAvailableStorage()
    {
        File file = Environment.getExternalStorageDirectory();//获取SD卡的目录
        StatFs statfs = new StatFs(file.getAbsolutePath());
        long count = statfs.getAvailableBlocks();
        long size = statfs.getBlockSize();
        return count * size;
    }

    /**
     * 保存图片到相册
     */
    public static void saveImageToAlbum(final String url)
    {
        saveImageToAlbum(url, null);
    }

    public static void saveImageToAlbum(final String url, final HttpBooleanCallBack callback)
    {
        new Thread()
        {
            @Override
            public void run()
            {
                Bitmap bitmap = getNetImageByUrl(url);
                if (bitmap != null)
                {
                    saveBitmap(bitmap, callback);
                }else
                {
                    LoeHttp.handler.post(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            callback.callback(false);
                        }
                    });
                }
            }
        }.start();
    }

    private static Bitmap getNetImageByUrl(String url)
    {
        Bitmap bitmap = null;
        try
        {
            if(url.startsWith("https"))
            {
                HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
                connection.setConnectTimeout(6000); //超时设置
                connection.setDoInput(true);
                connection.setUseCaches(false); //设置不使用缓存
                connection.connect();
                InputStream inputStream = connection.getInputStream();
                bitmap = BitmapFactory.decodeStream(inputStream);
                inputStream.close();
            }else if(url.startsWith("http"))
            {
                HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                connection.setConnectTimeout(6000); //超时设置
                connection.setDoInput(true);
                connection.setUseCaches(false); //设置不使用缓存
                connection.connect();
                InputStream inputStream = connection.getInputStream();
                bitmap = BitmapFactory.decodeStream(inputStream);
                inputStream.close();
            }else
            {
                bitmap = BitmapFactory.decodeFile(url);
            }
        } catch (Exception e)
        {
            e.printStackTrace();

        }
        return bitmap;
    }

    public static void saveBitmap(Bitmap bitmap, final HttpBooleanCallBack callback)
    {
        try
        {
            //创建一个保存的Uri
            ContentValues values = new ContentValues();
            //设置图片名称
            values.put(MediaStore.Images.Media.DISPLAY_NAME, "loe" + System.currentTimeMillis() + ".png");
            //设置图片格式
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
            //设置图片路径
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
            {
                values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
            }
            Uri saveUri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            if (saveUri.toString().isEmpty())
            {
                LoeHttp.handler.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        callback.callback(false);
                    }
                });
                return;
            }
            OutputStream outputStream = context.getContentResolver().openOutputStream(saveUri);
            //将位图写出到指定的位置
            //第一个参数：格式JPEG 是可以压缩的一个格式 PNG 是一个无损的格式
            //第二个参数：保留原图像90%的品质，压缩10% 这里压缩的是存储大小
            //第三个参数：具体的输出流
            if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream))
            {
                LoeHttp.handler.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        callback.callback(true);
                    }
                });
            }
            else
            {
                LoeHttp.handler.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        callback.callback(false);
                    }
                });
            }
        } catch (Exception e)
        {
            e.printStackTrace();
            LoeHttp.handler.post(new Runnable()
            {
                @Override
                public void run()
                {
                    callback.callback(false);
                }
            });
        }
    }
}
